package com.digitalchina.lxnsy.fragment;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.FarmAccountsStatisticsVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.FarmAccountStatisticsHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2018/8/31 14:49
 * 修改备注：
 * ================================================
 */
public class FarmAccountStatisticsFragment extends BaseV4Fragment implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.tv_out)
    TextView tvOut;
    @Bind(R.id.tv_in)
    TextView tvIn;
    @Bind(R.id.tv_total)
    TextView tvTotal;
    @Bind(R.id.tv_money)
    TextView tvMoney;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;

    int mYear;
    int mMonth;
    int mDayOfMonth;

    private RecyclerArrayAdapter adapter;
    private String date = "";
    private String productPlanId = "";
    private String type = "1"; // 收入支出类型 0-收入 1-支出

    private List<FarmAccountsStatisticsVO> voList = new ArrayList<>();
    private String num = "总支出合计";

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_farm_acc_statistics);
    }

    @Override
    public void initMember() {
        productPlanId = getArguments().getString("productPlanId");

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        if (mMonth <= 9)
            date = mYear + "-0" + (mMonth + 1);
        else
            date = mYear + "-" + (mMonth + 1);
        tvTime.setText(date);


        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.addItemDecoration(Utils.setDividerDecoration(getActivity(), 1, 0, 0));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(getActivity()) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new FarmAccountStatisticsHolder(parent);
            }
        });

        onRefresh();
    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_FARM_ACCOUNT_STATISTICS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_FARM_ACCOUNT_STATISTICS_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "farmAccounts", FarmAccountsStatisticsVO.class);
        String totalIncome = FastJsonUtil.getString(object.toString(), "totalIncome");
        String numbers = FastJsonUtil.getString(object.toString(), "numbers");

        String total = num + "（" + numbers + "）";
        tvMoney.setText("￥" + totalIncome);
        tvTotal.setText(total);

        adapter.clear();
        adapter.addAll(voList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_time, R.id.tv_out, R.id.tv_in})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_time:
                showDatePicker();
                break;
            case R.id.tv_out:
                type = "1";
                num = "总支出合计";
                tvType.setText("支出排行榜");
                tvOut.setTextColor(getResources().getColor(R.color.app_color));
                tvOut.setBackgroundResource(R.color.colorWhite);
                tvIn.setTextColor(getResources().getColor(R.color.colorWhite));
                tvIn.setBackgroundResource(R.color.app_color);
                onRefresh();
                break;
            case R.id.tv_in:
                type = "0";
                num = "总收入合计";
                tvType.setText("收入排行榜");
                tvIn.setTextColor(getResources().getColor(R.color.app_color));
                tvIn.setBackgroundResource(R.color.colorWhite);
                tvOut.setTextColor(getResources().getColor(R.color.colorWhite));
                tvOut.setBackgroundResource(R.color.app_color);
                onRefresh();
                break;
        }
    }

    @Override
    public void onRefresh() {
        BusinessPlan.farmAccountStatistics(getActivity(), productPlanId, date, type, mHandler);
    }

    /**
     * 显示日期选择
     */
    private void showDatePicker() {


        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                month = month + 1;
                if (month <= 9)
                    date = year + "-0" + month;
                else
                    date = year + "-" + month;
                tvTime.setText(date);
                onRefresh();
            }
        }, mYear, mMonth, mDayOfMonth);

        datePickerDialog.show();
    }
}
